<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .chat-container {
            height: 400px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            overflow-y: auto;
            background-color: #fafafa;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 8px;
            max-width: 80%;
        }
        .user-message {
            background-color: #007bff;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        .assistant-message {
            background-color: #e9ecef;
            color: #333;
        }
        .system-message {
            background-color: #fff3cd;
            color: #856404;
            font-style: italic;
            text-align: center;
        }
        .input-container {
            display: flex;
            gap: 10px;
        }
        #messageInput {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .status {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
            font-size: 12px;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .controls {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        #sessionId {
            font-family: monospace;
            background-color: #f8f9fa;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket 聊天测试</h1>
        
        <div class="controls">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
            <button id="clearBtn" onclick="clearSession()" disabled>清除会话</button>
            <span>会话ID: <span id="sessionId">未连接</span></span>
        </div>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div id="chatContainer" class="chat-container"></div>
        
        <div class="input-container">
            <input type="text" id="messageInput" placeholder="输入消息..." disabled>
            <label><input type="checkbox" id="audioOutput"> 启用语音输出</label>
            <button id="sendBtn" onclick="sendMessage()" disabled>发送</button>
        </div>
    </div>

    <script>
        let ws = null;
        let sessionId = null;
        let isConnected = false;

        function updateStatus(message, connected) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = `status ${connected ? 'connected' : 'disconnected'}`;
            isConnected = connected;
            
            // 更新按钮状态
            document.getElementById('connectBtn').disabled = connected;
            document.getElementById('disconnectBtn').disabled = !connected;
            document.getElementById('clearBtn').disabled = !connected;
            document.getElementById('messageInput').disabled = !connected;
            document.getElementById('sendBtn').disabled = !connected;
        }

        function addMessage(content, type = 'assistant') {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}-message`;
            messageDiv.textContent = content;
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function connect() {
            const wsUrl = 'ws://localhost:8000/chat/ws';
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function(event) {
                updateStatus('已连接', true);
                addMessage('WebSocket连接已建立', 'system');
                
                // 连接建立后立即发送session_info
                const currentSessionId = sessionId || `session_${Date.now()}`;
                ws.send(JSON.stringify({
                    type: 'session_info',
                    session_id: currentSessionId
                }));
            };
            
            ws.onmessage = function(event) {
                const data = JSON.parse(event.data);
                console.log('收到消息:', data);
                
                switch(data.type) {
                    case 'session_info':
                        sessionId = data.session_id;
                        document.getElementById('sessionId').textContent = sessionId;
                        addMessage(`会话已创建: ${sessionId}`, 'system');
                        break;
                        
                    case 'session_confirmed':
                        sessionId = data.session_id;
                        document.getElementById('sessionId').textContent = sessionId;
                        addMessage(`Session ID已确认: ${sessionId}`, 'system');
                        break;
                        
                    case 'response_start':
                        addMessage('AI开始回复...', 'system');
                        break;
                        
                    case 'response_chunk':
                        // 查找最后一个assistant消息并追加内容
                        const messages = document.querySelectorAll('.assistant-message');
                        const lastMessage = messages[messages.length - 1];
                        if (lastMessage && !lastMessage.dataset.completed) {
                            lastMessage.textContent += data.content;
                        } else {
                            const messageDiv = document.createElement('div');
                            messageDiv.className = 'message assistant-message';
                            messageDiv.textContent = data.content;
                            document.getElementById('chatContainer').appendChild(messageDiv);
                        }
                        document.getElementById('chatContainer').scrollTop = document.getElementById('chatContainer').scrollHeight;
                        break;
                        
                    case 'response_end':
                        // 标记最后一个assistant消息为完成
                        const allMessages = document.querySelectorAll('.assistant-message');
                        if (allMessages.length > 0) {
                            allMessages[allMessages.length - 1].dataset.completed = 'true';
                        }
                        addMessage('AI回复完成', 'system');
                        break;
                        
                    case 'pong':
                        console.log('收到心跳响应');
                        break;
                        
                    case 'session_cleared':
                        addMessage('会话记忆已清除', 'system');
                        break;
                        
                    case 'tts_start':
                        addMessage('开始语音合成...', 'system');
                        break;
                        
                    case 'tts_end':
                        if (data.audio_url) {
                            playAudioFromUrl(data.audio_url);
                            addMessage(`语音合成完成`, 'system');
                        }
                        break;
                        
                    case 'tts_error':
                        addMessage(`语音合成错误: ${data.message}`, 'system');
                        break;
                        
                    case 'error':
                        addMessage(`错误: ${data.message}`, 'system');
                        break;
                }
            };
            
            ws.onclose = function(event) {
                updateStatus('连接已断开', false);
                addMessage('WebSocket连接已断开', 'system');
                sessionId = null;
                document.getElementById('sessionId').textContent = '未连接';
            };
            
            ws.onerror = function(error) {
                updateStatus('连接错误', false);
                addMessage('WebSocket连接错误', 'system');
                console.error('WebSocket错误:', error);
            };
        }

        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            const audioOutput = document.getElementById('audioOutput').checked;
            
            if (message && ws && isConnected) {
                // 显示用户消息
                addMessage(message, 'user');
                
                // 发送消息到WebSocket
                const chatData = {
                    type: 'chat',
                    data: {
                        messages: [
                            {
                                role: 'user',
                                content: message
                            }
                        ],
                        query: null,
                        audio_output: audioOutput
                    }
                };
                
                ws.send(JSON.stringify(chatData));
                input.value = '';
            }
        }

        function clearSession() {
            if (ws && isConnected) {
                ws.send(JSON.stringify({
                    type: 'clear_session'
                }));
            }
        }

        function playAudioFromUrl(audioUrl) {
            try {
                // 构建完整的音频URL
                const fullUrl = window.location.origin + audioUrl;
                console.log('播放音频URL:', fullUrl);
                
                // 直接使用URL创建音频对象并播放
                const audio = new Audio(fullUrl);
                audio.play().catch(error => {
                    console.error('音频播放失败:', error);
                    addMessage('音频播放失败', 'system');
                });
                
                // 播放完成事件
                audio.addEventListener('ended', () => {
                    console.log('音频播放完成');
                });
                
                // 播放错误事件
                audio.addEventListener('error', (error) => {
                    console.error('音频播放错误:', error);
                    addMessage('音频播放错误', 'system');
                });
                
            } catch (error) {
                console.error('音频处理失败:', error);
                addMessage('音频处理失败', 'system');
            }
        }

        function playAudio(base64AudioData) {
            try {
                // 将base64数据转换为blob
                const binaryString = atob(base64AudioData);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                const blob = new Blob([bytes], { type: 'audio/mp3' });
                
                // 创建音频URL并播放
                const audioUrl = URL.createObjectURL(blob);
                const audio = new Audio(audioUrl);
                audio.play().catch(error => {
                    console.error('音频播放失败:', error);
                    addMessage('音频播放失败', 'system');
                });
                
                // 播放完成后清理URL
                audio.addEventListener('ended', () => {
                    URL.revokeObjectURL(audioUrl);
                });
            } catch (error) {
                console.error('音频处理失败:', error);
                addMessage('音频处理失败', 'system');
            }
        }

        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 定期发送心跳
        setInterval(function() {
            if (ws && isConnected) {
                ws.send(JSON.stringify({
                    type: 'ping',
                    timestamp: new Date().toISOString()
                }));
            }
        }, 30000); // 每30秒发送一次心跳
    </script>
</body>
</html>